<?php

class my extends bhCommon {

    public function __construct()
    {
        parent::__construct();
    }


    public function index()
    {
        $images = array(
            'login_image' => $this->images('login_image', 'login.png'),
            'xx' => $this->image_url . 'ic-pi09.png',
            'mz' => $this->image_url . 'ic-pi12.png',
            'my_bg' => $this->images('my_bg', 'my_bg.png'),
            'customer_img' => getImage(getConfig('customer_img'))
        );
        $config = array(
            'currency_name' => getConfig('currency_name'),
            'grid_ad' => getConfig('grid_ad'),
            'contact_type' => getConfig('contact_type', 1),
            'qq_group_id' => getConfig('qq_group_id'),
            'official_account_img' => getImage(getConfig('official_account_img')),
            'ad_type' => getConfig('ad_type', 1),
            'withdrawal_state' => getConfig('withdrawal_state', 1),
            'my_withdrawal_txt' => getConfig('my_withdrawal_txt', '现金奖励'),
        );
        $config['ad_show_type'] = $this->rising->get_ad_type($config['ad_type']);
        $sql = "SELECT COUNT(*) FROM " . prefix('day') . " WHERE member_id={$this->member['id']} AND clock > 0";
        $all_nun = p_fetchcolumn($sql) ? : 0;

        $program = p_getcolumn('program', array('position' => 1), 'COUNT(*)') ? : 0;

        $data = array(
            'is_auth' => $this->is_auth,
            'images' => $images,
            'config' => $config,
            'all_nun' => $all_nun,
            'program' => $program,
            'member' => $this->member,
            'audit_model' => audit_model(),
            'isQqhome' => $this->rising->isQqhome()
        );
        $this->json($data);
    }



    public function cash()
    {
        $first_presentation = getConfig('first_presentation', 10);
        $follow_up_presentation = getConfig('follow_up_presentation', 10);
        $bag_daily_upper = getConfig('bag_daily_upper');

        $cash_explain = getConfig('cash_explain');
        $cash_explain = $cash_explain ? json_decode($cash_explain, true) : '';

        $least_money = $this->member['cash'] > 0 ? $follow_up_presentation : $first_presentation;

        $this->member['payment_code_url'] = getImage($this->member['payment_code']);

        $audit_model = audit_model() || getConfig('withdrawal_state') == 2;
        if ($audit_model) {
            $share_text = '真有趣';
			$tx = '';
        } else {
            $share_text = '邀请好友，一起领红包';
			$tx = '提现';
        }
		

        $data = array(
            'member' => $this->member,
            'least_money' => $least_money,
            'cash_explain' => $cash_explain,
            'images' => array(
                'bg' => $this->images('cash_bg', 'userinfo_bg.png')
            ),
            'cash_type' => getConfig('cash_type', 2),
            'first_presentation' => $first_presentation,
            'follow_up_presentation' => $follow_up_presentation,
            'bag_daily_upper' => $bag_daily_upper,
            'share_text' => $share_text,
            'tx' => getConfig('withdrawal_button_txt', '提现'),
            'audit_model' => $audit_model,
            'qq' => $this->member['qq']
        );
        if (isQq()) {
            if ($cash_money = getConfig('cash_money')) {
                $cash_money = json_decode($cash_money, true);
                $data['exchange_amount'] = $cash_money;
            }

        }

        $this->json($data);
    }


    /**
     * 提现
     */
    public function withdrawals()
    {
        if ($this->member['is_block'] == 2) {
            $this->json(getConfig('block_msg', '打卡失败'), 2);
        }
        $money = $this->get('money', 0);

        if ($money <= 0) {
            $this->json('提现金额需要大于0元', 2);
        }

        $cash_num = p_getcolumn('withdrawals', array('member_id' => $this->member['id']), 'COUNT(*)') ? : 0;

        $cash_num = $cash_num + 1;
        $condition = p_get('withdrawals_condition', array('number' => $cash_num));
        if ($condition) {

            if ($condition['money'] != $money) {
                $this->json('本次只能提现' . $condition['money'] . '元', 2);
            }

            if ($condition['click_day'] > 0) {
                $sql = "SELECT COUNT(*) FROM " . prefix('day') . " WHERE member_id={$this->member['id']} AND clock>0";
                $days = p_fetchcolumn($sql) ? : 0;
                if ($condition['click_day'] > $days) {
                    $this->json('本次提现还需要坚持打卡' . ($condition['click_day'] - $days) . '天', 2);
                }
            }

            if ($condition['share_num'] > 0) {
                $share_num = p_getcolumn('member', array('parent_id' => $this->member['id']), 'COUNT(*)') ? : 0;
                //$this->json(($condition['share_num'] . '_' . $share_num . '_' . $this->member['id']), 2);
                if ($condition['share_num'] > $share_num) {
                    $this->json('本次提现还需要邀请' . ($condition['share_num'] - $share_num) . '人', 2);
                }
            }

        } else {
            if ($this->member['cash'] > 0) {
                $follow_up_presentation = getConfig('follow_up_presentation');
                if ($money < $follow_up_presentation) {
                    $this->json('非首笔提现金额需满' . $follow_up_presentation, 2);
                }
            } else {
                $first_presentation = getConfig('first_presentation');
                if ($money != $first_presentation) {
                    $this->json('首次只能提现' . $first_presentation . '元', 2);
                }
            }

            $bag_daily_upper = getConfig('bag_daily_upper', 100);

            $time = strtotime(date('Y-m-d', time()));
            $sql = "SELECT SUM(money) FROM " . prefix('withdrawals') . " WHERE member_id={$this->member['id']} AND created>={$time}";
            if (pdo_fetchcolumn($sql) + $money > $bag_daily_upper) {
                $this->json('每天提现上限为' . $bag_daily_upper . '元', 2);
            }

            $withdrawals_day_number = getConfig('withdrawal_day_frequency', 2);
            $sql = "SELECT COUNT(*) FROM " . prefix('withdrawals') . " WHERE member_id={$this->member['id']} AND created>={$time}";
            if (pdo_fetchcolumn($sql) >= $withdrawals_day_number) {
                $this->json('每天提现次数为' . $withdrawals_day_number . '次，请明天再来', 2);
            }


            $sign_days = getConfig('sign_days', 0);
            if ($sign_days > 0) {
                $sql = "SELECT COUNT(*) FROM " . prefix('day') . " WHERE member_id={$this->member['id']} AND clock>0";
                $days = p_fetchcolumn($sql) ? : 0;
                if ($sign_days > $days) {
                    $this->json('坚持打卡' . $sign_days . '天才能提现', 2);
                }
            }
        }

        $m_update = array(
            'cash' => $this->member['cash'] + 1
        );

        $cash_type = getConfig('cash_type', 2);
        if (isQq() && $cash_type == 1) {
            $qq = $this->get('qq');
            if (empty($qq)) {
                json('请填写当前qq号', 2);
            }
            $m_update['qq'] = $qq;
            //p_update('member', array('qq' => $qq), array('id' => $this->member['id']));
        }

        $cash_reviewed = getConfig('cash_reviewed');

        $insert = array(
            'member_id' => $this->member['id'],
            'money' => $money,
            'success_time' => time(),
            'type' => $cash_type,
            'status' => 1,
            'created' => time()
        );

        if ($cash_type == 1 && $money < $cash_reviewed) {
            $insert['status'] = 2;
        }


        if ($cash_type == 2) {
            $insert['payment_code'] = $this->get('payment_code');
            if (empty($insert['payment_code'])) {
                $this->json('请上传收款码', 2);
            }
            $m_update['payment_code'] = $insert['payment_code'];
        }

        pdo_begin();
        try{
            if (!$this->rising->change_money($this->member['id'], $money, 2)) {
                throw new Exception($this->rising->error);
            }
            if (!p_insert('withdrawals', $insert)) {
                throw new Exception('提现失败');
            }
            $pid = pdo_insertid();
            if ($insert['status'] == 2) {

                $this->setPayment();
                if (isQq()) {
                    if (!$this->rising->qqCash($this->member['id'], $money, '', $pid)) {
                        throw new Exception($this->rising->error);
                    }
                } else {
                    if (!$this->rising->cash($money, $this->member['id'])) {
                        throw new Exception($this->rising->error);
                    }
                }

            }

            p_update('member', $m_update, array('id' => $this->member['id']));

            pdo_commit();
            $this->json('');
        } catch (Exception $e) {
            pdo_rollback();
            $this->json($e->getMessage(), 0);
        }
    }


    public function login()
    {
        $iv = $this->get('iv');
        $encryptedData = $this->get('encryptedData');

        $wxbd = new WXBizDataCrypt($this->w['uniaccount']['key'], $this->session_key);

        $res = $wxbd->decryptData($encryptedData, $iv, $data);
        if ($res != ErrorCode::$OK) {
            //p_delete('token', array('member_id' => $this->member['id']));
            $this->json('更新失败', -1);
        }

        $data = json_decode($data, true);
        $member_id = $this->member['id'];

        $update = array(
            'nickname' => $data['nickName'],
            'head' => $data['avatarUrl'],
            'city' => $data['city'],
            'province' => $data['province'],
            'country' => $data['country'],
            'sex' => $data['gender'],
        );

        p_update('member', $update, array('id' => $member_id));
        $this->json();
    }


    public function user()
    {
        $data = array(
            'member' => $this->member,
            'profit_subscribe_id' => getConfig('profit_subscribe_id')
        );
        $this->json($data);
    }



    public function addTips()
    {
        p_update('member', array('remind' => $this->member['remind'] + 1), array('id' => $this->member['id']));
        $this->json();
    }


    /**
     *
     */
    public function friend()
    {
        $config = array(
            'grid_ad' => getad(),
            'screen_ad' => getConfig('screen_ad'),
            'ad_type' => getConfig('ad_type', 1),
            'poster_bg' => $this->images('poster_bg', 'poster.jpg')
        );
        $config['ad_show_type'] = $this->rising->get_ad_type($config['ad_type']);

        $sql = "SELECT COUNT(*) FROM " . prefix('member') . " WHERE parent_id={$this->member['id']} AND head!=''";
        $friends_num = p_fetchcolumn($sql) ? : 0;

        $show_friends_num = getConfig('show_friends_num', 10);

        //$friends = p_getall('member', array('parent_id' => $this->member['id']), array(), '', 'id desc', $show_friends_num);


        $sql = "SELECT id,head,nickname FROM " . prefix('member') . " WHERE parent_id={$this->member['id']} AND head!='' ORDER BY id desc LIMIT {$show_friends_num}";
        $friends = p_fetchall($sql);



        $qr_code = createWxCode($this, $this->member['id'], 'bh_rising/pages/index/index', 'rising-' . $this->member['id'] . '.png');

        if ($friends) {
            foreach ($friends as & $value) {
                $value['day'] = $this->rising->get_clock_today($value['id']);
                $value['all_clock'] = p_getcolumn('day', array('member_id' => $value['id']), 'SUM(clock)') ? : 0;
            }
        }

        $data = array(
            'config' => $config,
            'qr_code' => $qr_code,
            'friends' => $friends,
            'friends_num' => $friends_num,
            'head' => headLocal($this, $this->member['head']),
            'audit_model' => !audit_model()
        );
        $this->json($data);
    }


    /**
     * 获取用户地址
     */
    public function getAddress()
    {
        $address = p_get('address', array('member_id' => $this->member['id']));
        $this->json(array('address' => $address));
    }


    /**
     * 设置地址
     */
    public function setAddress()
    {
        $data = array(
            'name' =>  $this->get('name'),
            'phone' =>  $this->get('phone'),
            'address' =>  $this->get('address'),
        );

        if ($address = p_get('address', array('member_id' => $this->member['id']))) {
            p_update('address', $data, array('id' => $address['id']));
        } else {
            $data['member_id'] = $this->member['id'];
            $data['created'] = time();
            p_insert('address', $data);
        }
        $this->json();
    }


    public function order()
    {
        $order = p_getall('order', array('member_id' => $this->member['id'], 'is_pay' => 2), array(),'', array('id desc')) ? : array();
        if ($order) {
            $status = array(
                1 => '未发货',
                2 => '已发货',
                3 => '已完成',
                4 => '已取消'
            );
            foreach ($order as & $value) {
                $value['goods'] = p_get('goods', array('id' => $value['goods_id']));
                $value['goods']['img'] = getImage($value['goods']['cover_image']);
                $value['created'] = date('Y-m-d H:i:s', $value['created']);
                $value['status_msg'] = $status[$value['status']];
            }
        }
        $images = array(
            'my_orders_nodata' => $this->image_url . 'my_orders_nodata.png',
            'my_express_icon' => $this->image_url . 'my_express_icon.png',
            'attention' => $this->image_url . 'attention.png',
        );
        $data = array(
            'orders' => $order,
            'currency_name' => getConfig('currency_name'),
            'cash_type' => getConfig('cash_type', 1),
            'images' => $images
        );
        $this->json($data);
    }


    public function moneyLog()
    {
        $log = p_getall('money_log', array('member_id' => $this->member['id']), array(), '', 'id desc');

        $types = array(
            '1' => '分红',
            '2' => '提现',
            '3' => '首次打卡赠送',
            '4' => '兑换红包商品',
            '5' => '兑换商品'
        );

        if ($log) {
            foreach ($log as & $value) {
                $value['type_msg'] = $types[$value['type']];
                $value['created'] = date('Y-m-d H:i:s', $value['created']);
            }
        }

        $data = array(
            'log' => $log,
            'food_name' => getConfig('food_name')
        );
        $this->json($data);
    }



    public function bindIds()
    {
        if ($this->member['ids']) {
            $this->json('您已经绑定过', 0);
        }
        $ids = $this->get('ids');
        $real_name = $this->get('real_name');

        if (empty($real_name)) {
            $this->json('请填写您的真实姓名', 0);
        }
        if (empty(validation_filter_id_card($ids))) {
            $this->json('请填写真确的身份证号', 0);
        }

        if (p_get('member', array('ids' => $ids))) {
            $this->json('该身份证号已经被使用', 0);
        }
        p_update('member', array('ids' => $ids, 'real_name' => $real_name), array('id' => $this->member['id']));
        $this->json();
    }


    public function getIds()
    {
        $data = array(
            'member' => $this->member
        );
        $this->json($data);
    }
}